package cn.springstudio.springui.template;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.google.android.material.tabs.TabLayout;

import java.util.Map;

import cn.springstudio.springui.R;
import cn.springstudio.springui.databinding.FragmentTabBinding;
import cn.springstudio.util.FragmentNavigation;

public abstract class TabFragment extends Fragment implements TabLayout.OnTabSelectedListener,
        FragmentNavigation.OnFragmentNavigationListener {

    FragmentTabBinding binding;
    FragmentNavigation navigation;
    Map<String, Fragment> fragmentMap;

    public TabFragment() {
    }

    public abstract Map<String, Fragment> getFragments();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        navigation = FragmentNavigation.instance(getChildFragmentManager(), R.id.container, this);
        fragmentMap = getFragments();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = FragmentTabBinding.inflate(inflater);
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        binding.tabLayout.addOnTabSelectedListener(this);
        for (String key : fragmentMap.keySet()) {
            binding.tabLayout.addTab(binding.tabLayout.newTab().setText(key));
        }
        binding.tabLayout.selectTab(binding.tabLayout.getTabAt(0));
    }

    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        navigation.navigationTo(tab.getPosition());
    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {
    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {
    }

    @Override
    public Fragment onCreateFragment(int position) {
        return fragmentMap.get(binding.tabLayout.getTabAt(position).getText());
    }
}